<template>
  <page-frame>
    <div class="addTemplate">
      <div class="toptitle">
        <div class="left">服务套餐 - 新增套餐</div>
        <div class="right">
          <div class="btns">
            <el-button v-show="this.$route.params.way==1" class="lightGreenBtn" @click="saveTemplate">保存</el-button>
            <el-button v-show="this.$route.params.way==2" class="lightGreenBtn" @click="saveChangeTemplate">提交</el-button>
            <router-link :to="{name:'servicePlanTemplate'}"><el-button>返回</el-button></router-link>
          </div>
        </div>
      </div>
      <div class="borderT"></div>
      <el-form :model="submitData" ref="submitData" :rules="rules" :label-position="labelPosition" label-width="100px" class="demo-ruleForm">
        <div class="panel">
          <div class="panel-title first">
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="grid-content bg-purple">基本信息</div>
              </el-col>
            </el-row>
          </div>
          <div class="panel-content">
            <el-row>
              <el-col :span="8" >
                <el-form-item label="套餐名称：" prop="comboName">
                  <el-input v-model="submitData.comboName" :disabled="status"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="套餐类别：" prop="type">
                  <el-select v-model="submitData.type" :disabled="status" @change="selectComboType" placeholder="请选择所属类别">
                    <el-option
                      v-for="item in comboTypeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="照护等级："  prop="lid">
                  <el-select v-model="submitData.lid" :disabled="status" placeholder="请选择照护等级">
                    <el-option
                      v-for="item in gradeList"
                      :label="item.lname"
                      :value="item.lid">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="套餐总价：" prop="price">
                  <el-input v-model="submitData.price" type="number" :disabled="status"></el-input>
                  <span>元</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="18">
                <el-form-item label="套餐描述：" style="margin-bottom: 0px">
                  <el-input
                    type="textarea"
                    :autosize="{ minRows: 3, maxRows: 8}"
                    placeholder="请输入套餐描述"
                    :disabled="status"
                    v-model="submitData.description"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="panel">
          <div class="panel-title free">
            <div class="grid-content bg-purple">服务项目</div>
          </div>
          <div class="tabChange" v-if="!status">
            <el-button :class="{lightGreenBtn:active==0}" @click="toggle">全部项目</el-button>
            <el-button :class="{lightGreenBtn:active==1}" @click="selected">已选择项目</el-button>
          </div>
          <div class="panel-content" v-if="!isChoose">
          <el-row>
            <el-table
              :data="serviceItem"
              border
              ref="multipleTable"
            >
              <el-table-column
                label="选择"
                width="80">
                <template scope="scope">
                  <el-checkbox v-model="scope.row.checked"></el-checkbox>
                </template>
              </el-table-column>
              <el-table-column
                label="工作时间"
                width="300">
                <template scope="scope">
                  <span v-if="scope.row.period==0 || scope.row.period==3">{{scope.row.dateListString}}</span>
                  <!--<span>{{scope.row.itemDateList | formateTimeToString}}</span>-->
                  <el-button type="text" size="small" v-if="scope.row.period==0 || scope.row.period==3" v-show="!status" @click.stop="adjustTime(scope.row)">工作时间</el-button>
                </template>
              </el-table-column>
              <el-table-column
                label="频次"
                width="230">
                <template scope="scope">
                  <el-row>
                    <el-col :span="14">
                      <el-select v-model="scope.row.period" :disabled="status" placeholder="" >
                        <el-option
                          v-for="item in frequencyList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="9">
                      <el-input @change="toNumber(scope.row)" v-if="scope.row.period!=0 && scope.row.period!=3" v-model="scope.row.num" :disabled="status"></el-input>
                    </el-col>
                    <el-col :span="1" v-if="scope.row.period!=0 && scope.row.period!=3"><span class="frequencyUnit">次</span></el-col>
                  </el-row>
                </template>
              </el-table-column>
              <el-table-column
                prop="typeName"
                label="项目类型"
                column-key="typeName">
              </el-table-column>
              <el-table-column
                prop="serviceName"
                label="服务项目"
                width="">
              </el-table-column>
              <el-table-column
                prop="typeName"
                label="项目类型"
                width="140"
                :filters="CONSTANT_SERVICE_COMBO_OPTION"
                :filter-method="filterTag"
                filter-placement="bottom-end">
                <template scope="scope">
                  <el-tag
                    :type="scope.row.typeName === '生活类' ? 'primary' : 'success'"
                    close-transition>{{scope.row.typeName}}</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </div>
          <div class="panel-content" v-if="isChoose">
              <el-table
                :data="multipleSelectionCurrent"
                border
                >
                <el-table-column
                  label="工作时间"
                  width="300">
                  <template scope="scope">
                    <span v-if="scope.row.period==0 || scope.row.period==3">{{scope.row.dateListString}}</span>
                    <!--<span>{{scope.row.itemDateList | formateTimeToString}}</span>-->
                    <el-button type="text" size="small" v-if="scope.row.period==0 || scope.row.period==3" v-show="!status" @click.stop="adjustTime(scope.row)">工作时间</el-button>
                  </template>
                </el-table-column>
                <el-table-column
                  label="频次"
                  width="230">
                  <template scope="scope">
                    <el-row>
                      <el-col :span="14">
                      <el-select v-model="scope.row.period" :disabled="status" placeholder="" >
                        <el-option
                        v-for="item in frequencyList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                      </el-select>
                      </el-col>
                      <el-col :span="9">
                      <el-input @change="toNumber(scope.row)" v-if="scope.row.period!=0 && scope.row.period!=3" v-model="scope.row.num" :disabled="status"></el-input>
                      </el-col>
                      <el-col :span="1" v-if="scope.row.period!=0 && scope.row.period!=3"><span class="frequencyUnit">次</span></el-col>
                    </el-row>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="typeName"
                  label="项目类型"
                  width="">
                </el-table-column>
                <el-table-column
                  prop="serviceName"
                  label="服务项目"
                  width="">
                </el-table-column>
              </el-table>
          </div>
        </div>
      </el-form>
      <!--选择工作时间的弹框-->
      <el-dialog title="工作时间" :visible.sync="showDialog" size="tiny"
                 :close-on-click-modal="false">
        <el-form :model="dialogData"  label-width="100px">
          <el-form-item label="项目名称">
            <el-col :span="18">
              <el-input v-model="dialogData.itemName" disabled></el-input>
            </el-col>
          </el-form-item>

          <el-form-item
            v-for="(workTime, index) in dialogData.workTimes"
            :label-width="formLabelWidth"
            :label="'工作时间' + (index + 1)"
            :prop="'workTimes.' + index + '.value'"
          >
            <el-col :span="18">
              <el-time-picker
                is-range
                v-model="dialogData.workTimes[index]"
                placeholder="选择时间范围"
                format="HH:mm">
              </el-time-picker>
            </el-col>
            <el-col :span="4" :offset="1">
              <el-button type="text" @click.prevent="removeTime(index)">删除</el-button>
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-col :span="5">
              <el-button type="text" @click.prevent="addTime()">新增工作时间段</el-button>
            </el-col>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogCancel">取 消</el-button>
          <el-button type="primary" @click="dialogConfirm">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </page-frame>
</template>

<script >
  import comboApi from '../../service/serManagement/comboApi'
  import commonJs from '../../config/common';
  import {CONSTANT_SERVICE_COMBO_OPTION} from '../../config/constant'
  const dialogDefaultData = {
    itemName:"",
    workTimes: [],
  };
  const submitDefaultData = {
    addServiceComboItemInfoDTOs: [],
    comboId: 0,
    comboName: "",
    createTime: "",
    createUser: "",
    deleted: 0,
    description: "",
    lid:"",
    orgId: "",
    price: null,
    tenantId: "",
    type: 1,
    updateTime: "",
    updateUser: ""
  };
  export default {
    data () {
      return {
        comboTypeOptions:[{
          label:'基础套餐',
          value:1
        },{
          label:'增值套餐',
          value:2
        }],
        comboType:1,
        status:false,
        formLabelWidth:'100px',
        labelPosition: 'right',
        CONSTANT_SERVICE_COMBO_OPTION,
        isChoose:false,
        currentTypeId:0,
        currentPage:1,
        currentComboId:0,
        multipleSelection: [],
        multipleSelectionCurrent:[],
        ruleForm:{
          packageName:'',
          grade:[],
          totalMoney:'',
        },
        submitData:JSON.parse(JSON.stringify(submitDefaultData)),
        serviceItem:[],
        active:0,
        gradeList:[],
        frequencyList:[{
          value:0,
          label:'每天'
        },{
          value:1,
          label:'每周'
        },{
          value:2,
          label:'每月'
        },{
          value:3,
          label:'任意'
        }],
        showDialog:false,
        dialogData:JSON.parse(JSON.stringify(dialogDefaultData)),
        newWorkTime: [],
        currentRowObj:{},
        rules: {
          comboName: [
            {required: true, message: '请输入套餐名称', trigger: 'blur'},
            {min: 1, max: 64, message: '长度在 1 到 64 个字符', trigger: 'blur'}
          ],
          type: [
            {type:"number",required: true, message: '请选择套餐类别', trigger: 'change'}
          ],
          lid: [
            {type:"number",required: true, message: '请选择照护等级', trigger: 'change'}
          ],
          price: [
            {required: true, message: '请输入套餐总价', trigger: 'blur'}
          ]
        },
        oldRowObj:{
          itemDateList:[]
        },
      }
    },
    beforeRouteEnter(to, from, next){
      next(vm=>{
        vm.getServiceItem();
      })
    },
    methods: {
      init() {
        let self = this;
        self.currentComboId = self.$route.params.comboId;
        self.getGrade();//获取照护等
        self.submitData = JSON.parse(JSON.stringify(submitDefaultData));
        self.serviceItem = [];
        if(self.$route.params.way==1) {//新增
          self.status = false;
          self.getServiceItem();//获取服务项目
        }else if(self.$route.params.way==0){//详情
          self.status = true;
          self.isChoose = true;
          self.getComboDetail();//获取服务套餐详情
        }else{//编辑
          self.status = false;
          self.getComboDetail();//获取服务套餐详情
        }
      },
      /**
       * 选择套餐类别
       */
      selectComboType(val){
        if(val=='1'){//基础套餐
          this.comboType = 1;
          this.getServiceItem();
        }else{
          this.comboType = 2;
          this.getServiceItem();
        }
      },
      /**
       * 获取照护等级
       */
      getGrade(){
        let self = this;
        comboApi.getCareGrade().then(function(response){
          self.gradeList = response.body.data;
        })
      },
      /**
       * 获取服务项目
       */
      getServiceItem(){
        let self = this;
        self.serviceItem = [];
        comboApi.getServiceList(self.currentTypeId,0,self.comboType).then(function(response){
          self.serviceItem = response.body.data;
//          for(var item of self.serviceItem){
//            item.dateListString = commonJs.formateTimeToString(item.itemDateList);
//          };
          self.getDateListString(self.serviceItem);
          self.getTypeName(self.serviceItem);//根据typeId还原typeName
          self.changeItem();//已选择项目替换全部项目
          self.toggleSelection();
        });
      },
      /**
       * 获取服务套餐详情
       */
      getComboDetail(){
        let self = this;
        comboApi.getComboDetail(self.currentComboId).then(function (response) {
          self.serviceItem = response.body.data.comboItemIds;
          self.submitData.comboName = response.body.data.comboName;
          self.submitData.price = response.body.data.price;
          self.submitData.lid = response.body.data.lid;
          self.submitData.type = response.body.data.type;
          self.comboType = response.body.data.type;
          self.submitData.description = response.body.data.description;
          self.multipleSelection = response.body.data.comboServiceItemListDTOs;
          self.multipleSelectionCurrent = response.body.data.comboServiceItemListDTOs;
          self.getTypeName(self.multipleSelection);//根据typeId还原typeName
          self.getServiceItem();//获取服务项目
          self.getDateListString(self.multipleSelectionCurrent);
          self.getDateListString(self.multipleSelection);
//          for(var item of self.multipleSelectionCurrent){
//            item.dateListString = commonJs.formateTimeToString(item.itemDateList);
//          };
//          for(var item of self.multipleSelection){
//            item.dateListString = commonJs.formateTimeToString(item.itemDateList);
//          };
        })
      },
      /**
       * 根据typeId还原typeName
       */
      getTypeName(itemsList){
        for(var item of itemsList){
          item.typeName = "";
          switch (item.typeId){
            case 1:
              item.typeName = "生活类";
              break;
            case 2:
              item.typeName = "医疗类";
              break;
            case 3:
              item.typeName = "护理类";
              break;
            case 4:
              item.typeName = "康复类";
              break;
            case 5:
              item.typeName = "保健类";
              break;
            case 6:
              item.typeName = "增值类";
              break;
            case 7:
              item.typeName = "其他";
              break;
        }};
      },
      /**
       * 根据dateList还原dateListString
       */
      getDateListString(dateList){
        for(var item of dateList){
          item.dateListString = commonJs.formateTimeToString(item.itemDateList);
        };
      },
      /**
       * tab切换
       */
      toggle(){
        this.isChoose = false;
        this.active = 0;
        this.currentTypeId = 0;
        this.currentPage = 1;
      },
      /**
       * 已选择项目替换全部项目
       */
      changeItem(){
        for (var i=0; i< this.serviceItem.length;i++){
          for(var j=0; j< this.multipleSelection.length;j++){
            if(this.serviceItem[i].serviceId ==  this.multipleSelection[j].serviceId){
              this.serviceItem[i] = this.multipleSelection[j];
            };
          }};
      },
      /**
       * 项目是否被选中
       */
      toggleSelection() {
        let self = this;
        if( self.serviceItem.length >0 && self.multipleSelection.length > 0){
            for (var i=0; i< self.serviceItem.length;i++){
              for(var j=0; j< self.multipleSelection.length;j++){
                if(self.serviceItem[i].serviceId ==  self.multipleSelection[j].serviceId){
                  self.serviceItem[i].checked = true;
                };
              }};
        }else{
            console.debug("serviceItem或者multipleSelection为空");
        };
      },
      /**
       * 项目类别筛选
       */
      filterTag(value, row) {
        return row.typeName === value;
      },
      /**
       * 已选择
       */
      selected(){
        this.active = 1;
        this.isChoose = true;
        this.multipleSelectionCurrent = [];
        for (var i=0; i<this.serviceItem.length;i++) {
          if (this.serviceItem[i].checked) {
            this.multipleSelectionCurrent.push(this.serviceItem[i]);
          }
        }
      },
      /**
       * 频次中的字符串转换成数字
       */
      toNumber(row){
        row.frequencyNum = parseInt(row.frequencyNum);
      },
      /**
       * 删除已选择项目
       */
      delItem(index,serviceId){
        let self = this;
        self.multipleSelectionCurrent.splice(index, 1);
        for (var i=0; i<this.serviceItem.length;i++) {
          if (this.serviceItem[i].serviceId = serviceId) {
            self.serviceItem[i].checked = false;
          }
        }
      },
      /**
       * 获取已选中的项目，并对选择项目进行判断
       */
      getChooseItem(){
        let self = this;
        self.multipleSelectionCurrent = [];
        for (let i=0; i<self.serviceItem.length;i++) {
          if (self.serviceItem[i].checked) {
            if(self.serviceItem[i].period == "1" || self.serviceItem[i].period == "2"){
              if(self.serviceItem[i].num != ""){
                self.multipleSelectionCurrent.push(self.serviceItem[i]);
              }else{
                self.$message({
                  message: '已勾选项目中频次为每周/每月的项目，次数必填',
                  type: 'warning'
                });
                return false;
              };
            }else{
              self.multipleSelectionCurrent.push(self.serviceItem[i]);
            };
          }
        };
        return true;
      },
      /**
       * 判断套餐基本信息是否完整
       */
      completeBasics(){
       let self = this;
       let validate;
       self.$refs["submitData"].validate((valid) => {
            if (valid) {
              validate  = true;
            } else {
              validate  = false;
              return false;
            }
          });
       return validate;
      },
      /**
       * 按钮保存套餐
       */
      saveTemplate(){
        let self = this;
        let selectedItem = self.getChooseItem();
        let isComplete = self.completeBasics();
        if(selectedItem && isComplete){
          self.submitData.addServiceComboItemInfoDTOs = self.multipleSelectionCurrent;
          comboApi.addCombo(self.submitData).then(function (response) {
            if(response.body.status == 200){
              self.submitData = response.body.data;
              self.$message({
                message: '保存成功',
                type: 'success'
              });
              self.$router.push({name: 'servicePlanTemplate'});
            };
          },function () {
            self.$message({
              message: '保存失败',
              type: 'warning'
            });
          });
        }else {};
      },
      /**
       * 提交套餐修改
       */
      saveChangeTemplate(){
        let self = this;
        let selectedItem = self.getChooseItem();
        let isComplete = self.completeBasics();
        if(selectedItem && isComplete){
          self.submitData.comboId = self.currentComboId;
          self.submitData.addServiceComboItemInfoDTOs = self.multipleSelectionCurrent;
          comboApi.editCombo(self.submitData).then(function (response) {
            self.submitData = response.body.data;
            self.$message({
              message: '修改成功',
              type: 'success'
            });
            self.$router.push({name: 'servicePlanTemplate'});
          },function () {
            self.$message({
              message: '修改失败',
              type: 'warning'
            });
          });
        }else {};

      },
      /**
       * 调整工作时间
       */
      adjustTime(row){
        this.dialogData = JSON.parse(JSON.stringify(dialogDefaultData));
        this.currentRowObj = row;
        this.oldRowObj.itemDateList = row.itemDateList.slice(0);
        debugger;
        this.dialogData.itemName = row.serviceName;
        for(let date of row.itemDateList){
          if(typeof date[0] != "string"){
            date[0] = commonJs.formatTime(date[0]);
            date[1] = commonJs.formatTime(date[1]);
          }
          date[0] = new Date(1970,1,1,date[0].substring(0,2),date[0].substring(3,5));
          date[1] = new Date(1970,1,1,date[1].substring(0,2),date[1].substring(3,5));
        }
        this.dialogData.workTimes = row.itemDateList;
        this.showDialog = true;
      },
      /**
       * 新增工作时间段
       */
      addTime() {
        this.dialogData.workTimes.push(this.newWorkTime);
      },
      /**
       * 删除工作时间
       */
      removeTime(index) {
        this.dialogData.workTimes.splice(index, 1);
      },
      /**
       * 弹出框确认
       */
      dialogConfirm() {
        this.currentRowObj.itemDateList = this.dialogData.workTimes;
        this.currentRowObj.dateListString = commonJs.formateTimeToString2(this.currentRowObj.itemDateList);
        this.isChoose = true;
        window.setTimeout(res => {
          this.isChoose = false;
        },100);
        this.showDialog = false;
        this.newWorkTime = [];
        this.dialogData = JSON.parse(JSON.stringify(dialogDefaultData));
      },
      /**
       * 弹出框取消
       */
      dialogCancel() {
        this.newWorkTime = [];
        this.currentRowObj.itemDateList = this.oldRowObj.itemDateList;
        this.showDialog = false;
        this.dialogData = JSON.parse(JSON.stringify(dialogDefaultData));
      },
    },
    mounted: function () {
      this.init();
    },
  }
</script>
<style>
  .addTemplate .frequencyUnit{
    display:inline-block;
    height:36px;
    line-height:36px;
  }
  .addTemplate .tabChange{
    padding-left: 15px;
  }
  .el-table-filter__content .el-checkbox:first-child{
    display: none;
  }
</style>
